package us.mooresr.geartrack.server.handler;

import java.util.ArrayList;

import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;

import us.mooresr.geartrack.server.DAO;
import us.mooresr.geartrack.shared.action.GetAllItemsAction;
import us.mooresr.geartrack.shared.action.GetAllItemsResult;
import us.mooresr.geartrack.shared.model.Item;
import us.mooresr.geartrack.shared.model.ItemType;
import us.mooresr.geartrack.shared.model.Location;

import com.google.inject.Inject;
import com.googlecode.objectify.Query;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;

public class GetAllItemsActionHandler implements
		ActionHandler<GetAllItemsAction, GetAllItemsResult> {

	@Inject
	public GetAllItemsActionHandler() {
	}

	@Override
	public GetAllItemsResult execute(GetAllItemsAction action, ExecutionContext context)
			throws ActionException {
		DAO dao = new DAO();
		

		
		ArrayList<Item> itemList = new ArrayList<Item>();
		
		Query<Item> q = dao.ofy().query(Item.class);
		
		for (Item r : q) {
			
			// Add the location
			Long locationId = r.getHomeLocationId();
			Location location;
			if (locationId == null) {
				location = null;
			} else {
				location = dao.ofy().get(Location.class, locationId);
			}
			r.setLocation(location);
			
			Long itemTypeId = r.getItemTypeId();
			ItemType itemType;
			if (itemTypeId == null) {
				itemType = null;
			} else {
				itemType = dao.ofy().get(ItemType.class, itemTypeId);
			}
			r.setItemType(itemType);
			
			itemList.add(r);
		}
		
		return new GetAllItemsResult(itemList);
	}

	@Override
	public void undo(GetAllItemsAction action, GetAllItemsResult result,
			ExecutionContext context) throws ActionException {
	}

	@Override
	public Class<GetAllItemsAction> getActionType() {
		return GetAllItemsAction.class;
	}
}
